// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const { createProject, getProject, searchProject } = require("./db.js");
const { SuccessModel, ErrorModel } = require("models");
const { checkToken } = require("utils");

module.exports = {
  _before: async function () {
    // 通用预处理器
    const methodName = this.getMethodName();
    // 不需要token校验的接口白名单
    if (["get"].includes(methodName)) {
      return;
    }
    const { token } = this.getParams()?.[0] || {};
    try {
      const data = await checkToken(token);
      this.userId = data.id;
    } catch {
      throw new ErrorModel("请先登录后再进行操作！");
    }
  },
  async search({ data }) {
    const res = await searchProject({ ...data, userId: this.userId });
    if (res.err) {
      return new ErrorModel("查询失败！");
    }
    return new SuccessModel(res);
  },
  async add({ data }) {
    const timestamp = +new Date();
    const res = await createProject({ ...data, userId: this.userId, createdAt: timestamp });
    if (res.err) {
      return new ErrorModel("新建失败！");
    }
    return new SuccessModel(res.data);
  },
  async update() {},
  async get({ data }) {
    const res = await getProject(data.id);
    if (res.err) {
      return new ErrorModel("查询失败！");
    }
  },
};
